//
//  PhotoBrowserCell.m
//  Browser
//
//  Created by ZHY on 2017/7/11.
//  Copyright © 2017年 ZHY. All rights reserved.
//

#define kMinimumZoomScale 0.3
#define kMaximumZoomScale 2

#import "PhotoBrowserCell.h"
#import "UIImageView+WebCache.h"
#import "PhotoProgressView.h"   
#import "SDWebImageManager.h"
#import "SVProgressHUD.h"

@interface PhotoBrowserCell()<UIScrollViewDelegate>

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UIImageView *pic;
@property (nonatomic,strong) PhotoProgressView *progressView;

@property (nonatomic,strong) UIView *bottomView;
@property (nonatomic,assign) BOOL needEnlarge;


@end

@implementation PhotoBrowserCell

-(instancetype)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}

#pragma mark - setupUI 
-(void)setupUI {
    
    self.contentView.backgroundColor = [UIColor blackColor];
    self.needEnlarge = YES;

    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.scrollView.delegate = self;
    self.scrollView.userInteractionEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = YES;//是否显示侧边的滚动栏
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.scrollsToTop = NO;
    self.scrollView.scrollEnabled = YES;
    [self.contentView addSubview:self.scrollView];
    
    self.progressView = [[PhotoProgressView alloc] init];
    [self.contentView addSubview:self.progressView];
    self.progressView.bounds = CGRectMake(0, 0, 50, 50);
    self.progressView.center = CGPointMake([UIScreen mainScreen].bounds.size.width * 0.5, [UIScreen mainScreen].bounds.size.height*0.5);
    self.progressView.backgroundColor = [UIColor clearColor];
    self.progressView.hidden = YES;
    
    self.pic = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    [self.scrollView addSubview:self.pic];
    
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height-45, [UIScreen mainScreen].bounds.size.width, 45)];
    self.bottomView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:self.bottomView];
    
    
    //单击手势
    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [singleTapGesture setNumberOfTapsRequired:1];
    [self.scrollView addGestureRecognizer:singleTapGesture];
    //双击手势
    UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    [doubleTapGesture setNumberOfTapsRequired:2];
    [self.scrollView addGestureRecognizer:doubleTapGesture];
    //当系统检测不到双击手势时执行再识别单击手势
     [singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];
    
    [self.scrollView setMinimumZoomScale:kMinimumZoomScale];
    [self.scrollView setMaximumZoomScale:kMaximumZoomScale];
    
}

#pragma mark - event

//保存图片
-(void)saveImage {
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImageWriteToSavedPhotosAlbum(self.pic.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    });
}

//保存图片结果
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    }else {
        [self handleSaveStatus:NO];
        [SVProgressHUD showSuccessWithStatus:@"成功保存到相册"];
    }
}


//设置图片的位置
-(void)handleImgFrame {

    CGSize size = self.pic.image.size;
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = size.height*width/size.width;
    
    if (!self.pic.image) {
        self.pic.frame = CGRectMake(0, 0, width, [UIScreen mainScreen].bounds.size.height);
        self.scrollView.contentSize = CGSizeMake(width, [UIScreen mainScreen].bounds.size.height);
        return;
    }
    
    if (height>[UIScreen mainScreen].bounds.size.height || !self.pic.image) {
        self.pic.frame = CGRectMake(0, 0, width, height);
        self.scrollView.contentSize = CGSizeMake(width, height);
    }else {
        self.pic.frame = CGRectMake(0, ([UIScreen mainScreen].bounds.size.height - height)/2, [UIScreen mainScreen].bounds.size.width, height);
        self.scrollView.contentSize = CGSizeMake(width, [UIScreen mainScreen].bounds.size.height);
    }
}

//处理网络加载图片
-(void)handleDownloadImage:(NSString *)urlStr {

    __weak typeof(self) weakSelf = self;
    self.progressView.hidden = NO;
    SDWebImageDownloader *downloader = SDWebImageManager.sharedManager.imageDownloader;
    for (NSString *key in self.httpHeaderFieldDic.allKeys) {
        [downloader setValue:self.httpHeaderFieldDic[key] forHTTPHeaderField:key];
    }
    [weakSelf handleSaveStatus:NO];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.pic sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:nil options:SDWebImageRetryFailed| SDWebImageLowPriority| SDWebImageHandleCookies| SDWebImageAllowInvalidSSLCertificates progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"receivedSize:%ld======expectedSize:%ld",(long)receivedSize,(long)expectedSize);
                if (expectedSize>0.0001) {
                    weakSelf.progressView.progress = (receivedSize*1.0)/(expectedSize*1.0);
                    NSLog(@"progress:%f",weakSelf.progressView.progress);
                }
            });
        } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf handleImgFrame];
                weakSelf.progressView.hidden = YES;
                BOOL isEnable ;
                if (error) {
                    isEnable = NO;
                }else {
                    isEnable = YES;
                }
                [weakSelf handleSaveStatus:isEnable];
                for (NSString *key in self.httpHeaderFieldDic.allKeys) {
                    [downloader setValue:nil forHTTPHeaderField:key];
                }
            });
        }];
    });
}

//处理保存按钮的状态
-(void)handleSaveStatus:(BOOL)isEnable {
    if (self.delegate && [self.delegate respondsToSelector:@selector(settingSaveBtnStatus:)]) {
        [self.delegate settingSaveBtnStatus:isEnable];
    }
}

-(void)handleSingleTap:(UIGestureRecognizer *)gesture {
    
    NSLog(@"handleSingleTap");
    if (self.delegate && [self.delegate respondsToSelector:@selector(closePhotoBrowser)]) {
        [self.delegate closePhotoBrowser];
    }
}

- (void)handleDoubleTap:(UIGestureRecognizer *)gesture
{
    NSLog(@"handleDoubleTap");
    float newScale ;//zoomScale这个值决定了contents当前扩展的比例
    CGPoint center = [gesture locationInView:gesture.view];
    if (self.needEnlarge) {
        newScale = self.scrollView.zoomScale * kMaximumZoomScale;
    }else {
        newScale = 1;
        center = CGPointMake(center.x/kMaximumZoomScale, center.y/kMaximumZoomScale);
    }
    
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:center];
    [self.scrollView zoomToRect:zoomRect animated:YES];
    self.needEnlarge = !self.needEnlarge;
}

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
    CGRect zoomRect;
    zoomRect.size.height = self.scrollView.frame.size.height / scale;
    zoomRect.size.width  = self.scrollView.frame.size.width  / scale;
    zoomRect.origin.x = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
    return zoomRect;
}


#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.pic;
}

//当滑动结束时
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    //把当前的缩放比例设进ZoomScale，以便下次缩放时实在现有的比例的基础上
    NSLog(@"scale is %f",scale);
    if (scale > 1) {
        [self.scrollView setZoomScale:scale animated:NO];
        self.needEnlarge = NO;
    }else {
        [self.scrollView setZoomScale:1 animated:YES];
        self.needEnlarge = YES;
    }
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    
    CGRect frame = self.pic.frame;
    frame.origin.y = (self.scrollView.frame.size.height - self.pic.frame.size.height) > 0 ? (self.scrollView.frame.size.height - self.pic.frame.size.height) * 0.5 : 0;
    frame.origin.x = (self.scrollView.frame.size.width - self.pic.frame.size.width) > 0 ? (self.scrollView.frame.size.width - self.pic.frame.size.width) * 0.5 : 0;
    self.pic.frame = frame;
    self.scrollView.contentSize = CGSizeMake(self.pic.frame.size.width, self.pic.frame.size.height);
}

#pragma mark - set or get
-(void)setImgStr:(NSString *)imgStr {

    _imgStr = imgStr;
    self.pic.image = [UIImage imageNamed:imgStr];
    [self handleImgFrame];
}

-(void)setUrlStr:(NSString *)urlStr {

    _urlStr = urlStr;
    [self handleDownloadImage:urlStr];
}

@end
